<?php
	require_once 'init.php';
	
	if ( $_SERVER["REQUEST_METHOD"] == "POST" )
	{
		$usernc = $util->quotes($_POST["usernc"]);
		$password = $util->quotes($_POST["password"]);
		$confirmpassword = $util->quotes($_POST["confirmpassword"]);
		$company = $util->quotes($_POST["company"]);
		
		if ($usernc != "" && $password != "" && $password != $confirmpassword) 
		{
			if($util->check_email_regex($usernc)){
				//Check UserLogin
				if (! $adminDB->executeSQL("select fdLogin, fdName from ".$util->userdbName().".tbUser where fdLogin='".trim($usernc)."' or fdName ='".trim($usernc)."'", $connID)) {					
					//Try Insert User
					if ($adminDB->executeSQL("insert into ".$util->userdbName().".tbUser(fdLogin, fdName, fdCompany, fdPassword) values('".trim($usernc)."', '".trim($usernc)."', '".trim($company)."', md5('".trim($password)."'))", $connID)) 
					{
						$userid = mysql_insert_id();						
						//Insert User Email
						if (isset($usernc) && $usernc != ''){
							$sql = "insert into ".$util->userdbName().".tbEmail(fdUserID, fdEmail, fdDefault) values(".$userid.", '".trim($usernc)."', 0)";
							$adminDB->executeSQL($sql, $connID);
						}
						//Handle Session
						if (isset($_SESSION["unc"]) && $_SESSION["unc"] != "") 
						{
							unset($_SESSION["unc"]);
						}
						session_register("unc");
						$_SESSION["unc"] = trim($usernc);
						if (isset($_SESSION["un"]) && $_SESSION["un"] != "") 
						{
							unset($_SESSION["un"]);
						}
						session_register("un");
						$_SESSION["un"] = trim($usernc);
						if (isset($_SESSION['toUrl'])) 
						{
							echo "<script>window.location.href='".$_SESSION['toUrl']."';</script>";
						} 
						else 
						{
							echo "<script>window.location.href='regsuccess.php';</script>";
						}
					} 
					else 
					{
						echo "<script>alert('注册失败，请重试！');window.location.href='register.php';</script>";
					}
				} 
				else 
				{
					echo "<script>alert('该ID已经被他人注册！');window.location.href='register.php';</script>";
				}
			}
			else
			{
				echo "<script>alert('请填写标准的电子邮件格式！');window.location.href='register.php';</script>";
			}
		}
		else
		{
			echo "<script>alert('用户密码有误，请确认两次输入的密码一致！！');window.location.href='register.php';</script>";
		}
	}
?>